package com.guyu.app.common.remote;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.guyu.app.common.pojo.bo.LocationBO;
import com.guyu.app.common.pojo.properties.GaodeProperties;
import com.guyu.app.common.remote.request.MapInputTipsReq;
import com.guyu.app.common.remote.response.GaoDeDistrictRsp;
import com.guyu.app.common.remote.response.MapInputTipsRsp;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.lang.tuple.Pair;
import org.dromara.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class GaodeRemote {


    public static String GEOCODE_REGEO_URL = "https://restapi.amap.com/v3/geocode/regeo?output=json&location=%s&key=%s&radius=100&extensions=base";

    public static String COORDINATE_CONVERT_URL = "https://restapi.amap.com/v3/assistant/coordinate/convert?locations=%s&coordsys=gps&output=json&key=%s";

    public static String GRASP_ROAD_URL = "https://restapi.amap.com/v4/grasproad/driving?locations=%s&coordsys=gps&output=json&key=%s";

    public static String INPUT_TIPS_URL = "https://restapi.amap.com/v3/assistant/inputtips?key=%s&keywords=%s&location=%s&city=%s&datatype=poi";

    public static String DISTRICT_URL = "https://restapi.amap.com/v3/config/district?key=%s&keywords=%s&subdistrict=%s&extensions=base";

    @Autowired
    private GaodeProperties gaodeProperties;

    /**
     * 逆地理编码
     *
     * @param lng 经度
     * @param lat 维度
     * @return 定位地址
     */
    public LocationBO regeo(double lng, double lat) {
        String url = String.format(GEOCODE_REGEO_URL, lng + "," + lat, gaodeProperties.getKey());
        String result = HttpUtil.get(url, 10000);
        if (log.isDebugEnabled()) {
            log.info("高德地图逆地理编码接口请求成功.url:{},result:{}", url, result);
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if (!Objects.equals(jsonObject.getString("status"), "1")) {
            return null;
        }
        JSONObject regeocode = jsonObject.getJSONObject("regeocode");
        JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
        String formatted_address = regeocode.getString("formatted_address");

        Object city = addressComponent.get("city");
        if (Objects.isNull(city)) {
            city = addressComponent.get("province");
        }

        LocationBO locationBO = new LocationBO();
        locationBO.setLng(lng);
        locationBO.setLat(lat);
        locationBO.setAddress(formatted_address);
        locationBO.setCountry(addressComponent.getString("country"));
        locationBO.setProvince(addressComponent.getString("province"));
        locationBO.setCity(city.toString());
        locationBO.setDistrict(addressComponent.getString("district"));
        locationBO.setAdcode(addressComponent.getString("adcode"));
        return locationBO;
    }

    /**
     * 坐标转换
     *
     * @param lng 经度
     * @param lat 维度
     * @return 转换后的高德坐标
     */
    public Pair<String, String> coordinateConvert(double lng, double lat) {
        String url = String.format(COORDINATE_CONVERT_URL, lng + "," + lat, gaodeProperties.getKey());
        String result = HttpUtil.get(url, 1000);
        if (log.isDebugEnabled()) {
            log.info("高德地图坐标转换接口请求成功.url:{},result:{}", url, result);
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if (!Objects.equals(jsonObject.getString("status"), "1")) {
            return null;
        }
        String locations = jsonObject.getString("locations");
        String[] split = locations.split(",");
        if (split.length < 2) {
            return null;
        }
        return Pair.of(split[0], split[1]);
    }

    /**
     * 输入提示
     */
    public List<MapInputTipsRsp> inputTips(MapInputTipsReq req) {
        req.check();
        String location = "";
        if (Objects.nonNull(req.getLat()) && Objects.nonNull(req.getLng())) {
            location = req.getLng() + "," + req.getLat();
        }

        String url = String.format(INPUT_TIPS_URL, gaodeProperties.getKey(), req.getKeywords(), location, req.getCity());
        String result = HttpUtil.get(url, 1000);
        if (log.isDebugEnabled()) {
            log.info("高德地图输入提示接口请求成功.url:{},result:{}", url, result);
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if (!Objects.equals(jsonObject.getString("status"), "1")) {
            return Lists.newArrayList();
        }
        return jsonObject.getList("tips", MapInputTipsRsp.class);
    }

    /**
     * 行政区域查询
     */
    public List<GaoDeDistrictRsp> district(String adcode, Integer subdistrict) {

        String url = String.format(DISTRICT_URL, gaodeProperties.getKey(), adcode, subdistrict);
        String result = HttpUtil.get(url, 1000);
        if (log.isDebugEnabled()) {
            log.info("高德地图行政区域查询请求成功.url:{},result:{}", url, result);
        }
        JSONObject jsonObject = JSON.parseObject(result);
        if (!Objects.equals(jsonObject.getString("status"), "1")) {
            return null;
        }
        return jsonObject.getList("districts", GaoDeDistrictRsp.class);
    }
}
